package com.sxz.mall.order.interceptor;

import com.alibaba.fastjson.JSON;
import com.sxz.mall.common.constant.AuthConstant;
import com.sxz.mall.common.vo.MemberVO;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 自定义拦截器： 获取当前登录的用户信息
 * 1、继承HandlerInterceptor
 * 2、添加前置(后置，环绕等方法)
 * <p>
 * 需要单独添加配置，哪些接口需要拦截
 */
public class AuthInterceptor implements HandlerInterceptor {

//    @Autowired
//    StringRedisTemplate redisTemplate;


    // 本地线程对象 ThreadLocal   Map<Thread, Object>
    public static ThreadLocal<MemberVO> threadLocal = new ThreadLocal();

    private StringRedisTemplate stringRedisTemplate;

    public AuthInterceptor(StringRedisTemplate redisTemplate) {
        super();
        stringRedisTemplate = redisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String requestURI = request.getRequestURI();
        boolean match = new AntPathMatcher().match("/orderPay/**", requestURI);
        // 匹配路由
        if (match) {
            return true;
        }

        //        MemberVO memberVO = new MemberVO();
//        memberVO.setNickname("登录1号");
//        threadLocal.set(memberVO);

        System.out.println("order里面的拦截器，我是prehandle,主要功能是将用户登录信息保存到ThreadLocal");
        String s = stringRedisTemplate.opsForValue().
                get(AuthConstant.AUTH_SESSION_REDIS);
        if (s != null) {
            MemberVO memberVO = JSON.parseObject(s, MemberVO.class);
            threadLocal.set(memberVO);
            return true;
        }
        HttpSession session = request.getSession();
        session.setAttribute(AuthConstant.AUTH_SESSION_MSG, "请先登录");
        response.sendRedirect("http://sxz.auth.com/login.html");

        return false;
    }
}
